<?php
class cartController extends RPHP_Controller
{

    public function getsencondtype()
    {
        $m    = $this->model;
        $user = $m->checkAuth();
        if ($user) {
            $caid = $_POST['caid'];
            $data = $m->getSecondCategory($caid);
            echo json_encode($data);
        }
    }

    public function cart()
    {
        $tpl  = 'cart_empty';
        $m    = $this->model;
        $user = $m->checkAuth();
        if ($user) {

            $u = $m->getMemberInfo();

            if ($u['mobile'] == "") {
                $this->redirect("/user/update_account?type=mobile&a=m&c=cart");
            } else {

                $data = $m->getCart();

                if ($data['goods']) {
                    $tpl = '';
                }

                $this->view->user = $u;

                $this->view->data = $data;

                $this->display($tpl);

            }
        }

    }

    public function ajax()
    {
        $m    = $this->model;
        $user = $m->checkAuth(false);
        if ($user) {
            /// $data = array('code' => 400, "msg" => "");
            //是否存在限购商品
            if ($_POST['act'] == "purchasing_num") {
                $data = $m->purchasingGoods($_POST['cartids']);
            }
            echo json_encode($data);
        }
    }

    //AJAX
    public function goods_ajax()
    {

        $code = 800;

        $m    = $this->model;
        $goto = true;
        $user = $m->checkAuth(false);
        if ($user) {

            if ($_POST['act'] == "add") {
                $code = $m->addToCart($_POST);
            } elseif ($_POST['act'] == "update") {

                $cartid       = intval($_POST['cartid']);
                $goods_number = intval($_POST['goods_number']);
                $code         = $m->updateCart($cartid, $goods_number, $user['uid']);

            } elseif ($_POST['act'] == "remove") {

                $cartid = intval($_POST['cartid']);
                $code   = $m->removeCart($cartid);
            }
            // 获取区域信息
            elseif ($_POST['act'] == "region") {
                $data = $m->getRegion($_POST['parent_id']);
                if ($data) {
                    $code = array('code' => 200, 'data' => $data);
                } else {
                    $code = array('code' => 404);
                }

                $code = json_encode($code);
            }
            // 添加收货地址
            elseif ($_POST['act'] == "address_add") {
                $code = $m->saveAddress($_POST);
            }
        }

        echo $code;
    }

    //结算
    public function checkout()
    {

        $goto = true;

        $m    = $this->model;
        $user = $m->checkAuth();
        if ($user) {

            if ($_GET['cartid'] != "") {
                $isPurchasingGoods = $m->purchasingGoods($_GET['cartid']); //判断是否有限购商品
                if ($isPurchasingGoods['code'] == 200) {

                    $this->view->purchasing = $isPurchasingGoods['type'];
                    $cartid_arr             = explode(",", addslashes(htmlspecialchars(trim($_GET['cartid']))));
                    foreach ($cartid_arr as $r) {
                        $r = intval($r);
                        if ($r > 0) {
                            $cartid[$r] = $r;
                        }

                    }
                } else {
                    $cartid = 0;

                }

            }

            if ($cartid) {

                $shipping_fee  = 8;
                $express_money = 0;
                $reduce_price  = 0;

                $this->view->cartid = $cartid;
                $data               = $m->getCart(true, $cartid);
                $addressid          = 0;
                if ($_GET['addressid'] != "") {
                    $addressid = intval($_GET['addressid']);
                }
                $address = $m->getAddress($user['uid'], $addressid, true);

                foreach ($data['cart'] as $key => $value) {

                    if ($value['express_setting'] != "") {

                        $express_setting = json_decode($value['express_setting'], true);

                        if ($express_setting['no_sale'][$address['province_id']]) {

                            $data['cart'][$key]['word'] = '当前收货地址不支持销售';
                            $reduce_price += number_format($value['shop_price'] * $value['number'], 2, ".", '');

                            $this->view->no_sale +=1;

                        } else {
                            $data['cart'][$key]['word'] = '';
                        }

                        if ($express_setting['extra_money'][$address['province_id']] > 0) {
                            $data['cart'][$key]['word'] = '每件增加运费'.$express_setting['extra_money'][$address['province_id']].'元';
                            $express_money += $value['number'] * $express_setting['extra_money'][$address['province_id']];
                        }

                    }

                }

                $is_free_shipping = 0;
                if ($data['is_free_shipping']) {
                    $is_free_shipping = $data['is_free_shipping'];
                    $shipping_fee     = 0;
                }

                $shipping_fee += $express_money>0 ? $express_money : 0;

                $this->view->data             = $data;
                $this->view->is_free_shipping = $is_free_shipping;
                $this->view->declaration      = $data['declaration'];

                $total_price = $express_price = $goods_amount = $nopromote_price = $express_total_number = $express_total_weight = 0;

                //计算商品总价格
                if ($this->view->cartid) {
                    foreach ($this->view->data['cart'] as $k => $r) {

                        if ($this->view->data['goods'][$r['goods_id']] && $r['stocknumber'] >= $r['number'] && $this->view->cartid[$r['id']]) {
                            $goods = $this->view->data['goods'][$r['goods_id']];

                            if ($goods['is_promote'] == 0) {
                                $nopromote_price += number_format($r['shop_price'] * $r['number'], 2, ".", '');
                            }

                            //为计算运费统计商品数量和重量
                            // if($goods['is_free_shipping']==0){
                            // $express_total_number += $r['number'];
                            // $express_total_weight += $r['number'] * $goods['goods_weight'];
                            // }

                            $checkout_price      = number_format($r['shop_price'] * $r['number'], 2, ".", '');
                            $checkout_price_ximi = number_format($goods['ximi_price'] * $r['number'], 2, ".", '');
                            $coupon_total += $goods['coupon_price'] * $r['number'];
                            if ($goods['can_use_gold'] > 0) {
                                $gold_total += $checkout_price;
                            }

                            $goods_amount += $checkout_price;
                            $total_price += $checkout_price;
                            $total_price_ximi += $checkout_price_ximi;

                        }
                    }
                }

                //计算运费
                $total_price += $shipping_fee;
                $total_price -= $reduce_price;

                //获取收获地址信息
                $this->view->address = $address;

                if ($goods_amount > 0 || $total_price_ximi > 0) {

                    $balance = $m->getBalance();

                    $this->view->goods_amount     = number_format($goods_amount, 2, ".", "");
                    $this->view->total_price      = number_format($total_price, 2, ".", "");
                    $this->view->total_price_ximi = $total_price_ximi * 1;
                    $this->view->coupon_total     = $coupon_total;
                    $this->view->gold_total       = $gold_total;
                    $this->view->province         = $m->getRegion();
                    $this->view->shipping_fee     = $shipping_fee;

                    $this->view->balance = $balance;
                    $this->view->coupon  = $m->getCoupon();

                    $goto = false;
                    $this->display();

                } else {
                    $goto = true;
                }

            }

        }

        if ($goto) {
            $this->redirect("/cart/cart");
        }

    }

    // 选择收货地址
    public function address()
    {
        $m    = $this->model;
        $user = $m->checkAuth();
        if ($user) {
            $cartId           = trim($_GET['cartid']);
            $id               = intval($_GET['id']);
            $cartIds          = empty($cartIds) ? 0 : $cartId;
            $this->view->data = $m->getAddress($user['uid']);
            //$this->view->cartIds = $cartIds;
            $this->display();
        }
    }

    // 添加收货地址
    public function address_add()
    {
        $m    = $this->model;
        $user = $m->checkAuth();
        if ($user) {
            $data = $m->getRegion();
            if ($data[0]) {
                foreach ($data[0] as $region_id => $r) {
                    $region[] = array('name' => $r['region_name'], 'id' => $region_id);

                    if ($data[$region_id]) {
                        $fi = count($region) - 1;
                        foreach ($data[$region_id] as $sec_id => $s) {
                            $region[$fi]['sub'][] = array('name' => $s['region_name'], 'id' => $sec_id);

                            if ($data[$sec_id]) {
                                $si = count($region[$fi]['sub']) - 1;
                                foreach ($data[$sec_id] as $thr_id => $t) {
                                    $region[$fi]['sub'][$si]['sub'][] = array('name' => $t['region_name'], 'id' => $thr_id);
                                }
                            }
                        }
                    }
                }
            }
            $this->view->region = json_encode($region);
            $this->display();
        }
    }

    //AJAX
    public function cart_ajax()
    {

        $data['code'] = 800;
        $m            = $this->model;
        $user         = $m->checkAuth(false);
        if ($user) {
            $data = $m->addToCart($_POST);
        }

        echo json_encode($data);
    }

    //AJAX
    public function number_ajax()
    {

        $code = 800;
        $m    = $this->model;
        $user = $m->checkAuth();
        {

            $cartid       = intval($_POST['cartid']);
            $goods_number = intval($_POST['goods_number']);
            $code         = $m->updateCart($cartid, $goods_number);

            echo $code;
        }
    }

    //保存订单
    public function saveorder()
    {

        $m    = $this->model;
        $user = $m->checkAuth();
        if ($user['uid'] > 0 && $_POST['act'] == "save") {

            // print_r($_POST);

            $data = $m->saveOrder($_POST);

            if ($user['app'] == 1) {
                $data['transaction_type'] = 2;
            } else {
                $data['transaction_type'] = 1;
            }

            if ($data['code'] == 200) {

                // 抵扣后不需要支付
                if ($data['pay_status'] == 2) {

                    $this->redirect("/order/order");

                } elseif ($data['order_sn'] != "" && $data['pay_total_fee'] > 0 && $data['order_id'] > 0 && $this->c['pay'][$data['transaction_type']]) {

                    $para['channel_id']     = $this->c['pay'][$data['transaction_type']]['channel_id'];
                    $para['out_trade_no']   = $data['order_id'];
                    $para['out_trade_type'] = "ORDER";
                    $para['total_fee']      = $data['pay_total_fee'];
                    $para['timestamp']      = $_SERVER['REQUEST_TIME'];
                    ksort($para);
                    foreach ($para as $key => $value) {
                        $tmp[] = $key . "=" . $value;
                    }
                    $stringSignTemp = implode("&", $tmp) . "&channer_key=" . $this->c['pay'][$data['transaction_type']]['channer_key'];
                    $para['sign']   = strtoupper(md5($stringSignTemp));
                    $tmp[]          = "sign=" . $para['sign'];

                    $this->redirect($this->c['pay'][$data['transaction_type']]['gate_url'] . "?" . implode("&", $tmp));
                }

            } else {

                $this->redirect("/cart/failed?code=" . $data['code']);

            }

        }

    }

    //失败页面
    public function failed()
    {
        $this->view->code       = $_GET['code'];
        $this->view->error_code = $_GET['error_code'];
        $this->display();
    }

}
